//设置控件默认全屏显示、并禁用新建、打开、保存、关闭、另存为等工具栏按钮
function setFullScreenMode(){
	TANGER_OCX_OBJ.FullScreenMode=true;
	TANGER_OCX_OBJ.FileNew=false;
	TANGER_OCX_OBJ.FileOpen=false;
	TANGER_OCX_OBJ.FileClose=false;
	TANGER_OCX_OBJ.FileSave=false;
	TANGER_OCX_OBJ.FileSaveAs=false;
//	TANGER_OCX_OBJ.FilePrint=false;
}
//设置控件保存菜单按钮的是否可用
function setFileSaveBool(bool){
	TANGER_OCX_OBJ.FileSave=bool;
}
//用户留痕
function SetReviewMode(boolvalue) {
    TANGER_OCX_OBJ.ActiveDocument.TrackRevisions = boolvalue;
}
//提取用户痕迹
function TANGER_OCX_Revisions(userName) {
	
    var c, d, e, a = "", b = TANGER_OCX_OBJ.ActiveDocument.Revisions.Count;
    if (0 != b){
        for (c = 1; b >= c; c++){
        	var now = new Date(TANGER_OCX_OBJ.ActiveDocument.Revisions.item(c).date); 
    		var nowStr=now.getFullYear()+"-";
    		
    		var month=(now.getMonth()+1)<=9?"0"+(now.getMonth()+1):(now.getMonth()+1);
    		nowStr+=month+"-";
    		
    		var date=now.getDate()<=9?"0"+now.getDate():now.getDate();
    		nowStr+=date+" ";
    		
    		var hour=now.getHours()<=9?"0"+now.getHours():now.getHours();
    		nowStr+=hour+":";
    		
    		var minutes=now.getMinutes()<=9?"0"+now.getMinutes():now.getMinutes();
    		nowStr+=minutes+":";
    		
    		var seconds=now.getSeconds()<=9?"0"+now.getSeconds():now.getSeconds();
    		nowStr+=seconds;
    		
    		var author=TANGER_OCX_OBJ.ActiveDocument.Revisions.item(c).Author;
    		
    		if(author==userName){
            d = "";
            e = TANGER_OCX_OBJ.ActiveDocument.Revisions.item(c).Range.text;
            d = 1 == TANGER_OCX_OBJ.ActiveDocument.Revisions.item(c).TYPE ?"插入" : "删除";
            a += "【" 
            		+ author + "】" 
            		+ d + "内容： " + e + "  【时间】：" 
            		+ nowStr + "</br>";
    		}
        }
    }else{
    	a = "";
    }
    return a;
}
//进入或退出强制痕迹保留状态
function setMarkModify(boolvalue){
	   SetReviewMode(boolvalue);
	   enableReviewBar(!boolvalue);
}
//
function enableReviewBar(boolvalue){
	   TANGER_OCX_OBJ.ActiveDocument.CommandBars("Reviewing").Enabled=boolvalue;
	   TANGER_OCX_OBJ.ActiveDocument.CommandBars("Track Changes").Enabled=boolvalue;
	   TANGER_OCX_OBJ.IsShowToolMenu=boolvalue; //关闭或打开工具菜单
}
//接受所有修订
function acceptAllRevisions(){
	   TANGER_OCX_OBJ.ActiveDocument.AcceptAllRevisions();
}
//拒绝所有修订
function rejectAllRevisions(){
	   TANGER_OCX_OBJ.ActiveDocument.RejectAllRevisions();
}

/**
 * 创建ntko文档控件，返回文档控件js对象
 */
function TANGER_OCX_DoCreate(){
 	//var TANGER_OCX_OBJ = document.getElementById("TANGER_OCX");
    if(typeof(TANGER_OCX_OBJ) == 'undefined' || typeof(TANGER_OCX_OBJ.CreateNew) == 'undefined') {
        alert("init word/wps plugin error , please check word/wps plugin");
        return;
    }
    try{
		TANGER_OCX_OBJ.CreateNew('Word.Document'); //创建新的word文档
	}catch(err){
		TANGER_OCX_OBJ.CreateNew('wps.Document'); //创建新的word文档
	}
	return TANGER_OCX_OBJ;
}
/**
 *传入本地路径打开文档
 */
function TANGER_OCX_DoOpen (url) {
	var isSuccess = true;
	var TANGER_OCX_OBJ = document.getElementById("TANGER_OCX");
 	try{	  
      TANGER_OCX_OBJ.OpenFromURL(url);
 	}catch (e){
       isSuccess = false;
 	}
 	return isSuccess;
}
/**
 * 传入非本地文件路径通过服务器下载后打开文档
 */
function TANGER_OCX_DoOpen_WriteDocPath(docPath) {
	var url = global_var_CTX+"/documentContent/writeDoc?path=" + docPath;
// 	TANGER_OCX_DoCreate();
 	return TANGER_OCX_DoOpen(url);
}

//查询书签
function queryBookMarksStore(formKey, formId,documentName){
	var url = global_var_CTX+"/flowTrail/getFormDataAndFlowNotions?formId="+formId+"&formKey="+formKey;
    var dataForm=null;
	$.ajaxSettings.async = false;
	$.getJSON(url,  function (data) {
   	   dataForm=data.data;
 	});
 	$.ajaxSettings.async =true;

    var bookMarksStore = {};
    $(window.frames["pageframe"].document).find("*[data-bind]").each(function(idx, element){
		var key = $(element).attr("data-bind");
		var frontDateVal = $(element).val();
		//下拉框处理
		if($(element).is("input[inputMode='select']")){
			if($(element).attr("data")){
				var selectArray = $.parseJSON($(element).attr("data"));
				for(var i=0,len=selectArray.length;i<len;i++){
					if(selectArray[i].value==$(element).val()){
						frontDateVal=selectArray[i].text;
						break;
					}
				}
			}
		}
		//时间处理
		if($(element).is("input[inputMode='date']")){
			frontDateVal = $(element).val().substring(0,10);
		}

		//意见处理
		if($(element).is("input[inputMode='advice']")){
			frontDateVal = dataForm[key];
		}
        var dataValue = frontDateVal;
        if(($.type(dataValue)==="string" || $.type(dataValue)==="number")) {
			bookMarksStore[key] = dataValue;
		}
        
        if(($.type(dataValue)==="string" || $.type(dataValue)==="number")) {
			//特殊处理 阅文单时间格式处理 mm.dd
			if(key.indexOf("READ_TIME")>-1){
			   bookMarksStore[key] = dataValue.replace(/^(\d+)\-(\d+)\-(\d+)$/, "$2.$3");
			}
			//特殊处理 反馈意见时间
			else if(key == "FEEDBACK_TIME"){
			   var time = dataValue.substring(0,10);
			   bookMarksStore["FEEDBACK_MOTH"] = time.replace(/^(\d+)\-(\d+)\-(\d+)$/, "$2");
			   bookMarksStore["FEEDBACK_DAY" ] = time.replace(/^(\d+)\-(\d+)\-(\d+)$/, "$3");
			}
			else{
				bookMarksStore[key] = dataValue;
			}
		}

		//特殊处理 阅文单 打印两份，书签不能重复问题
		// 来文单位
		// 文号
		// 密级
		// 收文时间
		// 文件标题
		// 编号
		// 
		if(key == "FROM_ORG" || key == "DOCUMNET_CODE" || 
		   key == "SECRET_GRADE" || key == "RECEIVE_TIME" ||
		   key == "DOCUMENT_TITLE" || key == "SERIAL_NUMBER" ||
		   key == "DOCUMENT_IN_SEQ" 
		   ) {

           bookMarksStore[ "PAGE2_" + key] = bookMarksStore[key];  
		}
        
	});
    for(var key in dataForm) {
  		if($.type(dataForm[key])==="object" && dataForm[key].items!=null) {
			var items=dataForm[key].items;
			for(var i=0,len=items.length;i<len;i++){
				bookMarksStore["advice_content"+key]=items[i].content;
				bookMarksStore["advice_date"+key]= items[i].date.substring(0,10);
				bookMarksStore["advice_user"+key]=items[i].name;
		    }
		}
  	}  
    for(var key in dataForm) {
  		if($.type(dataForm[key])==="object" && dataForm[key].items!=null) {
			var items=dataForm[key].items;
			var adviceInfo = "";
			for(var i=0,len=items.length;i<len;i++){
				var line = "";
				// 姓名
				line += items[i].content + "  ";
				
				line += "  --" + items[i].name + "	";
				line += items[i].date.substring(0,10).replace(/(\d+)-(\d+)-(\d+)/g, "$2.$3") + "   ";
				adviceInfo += line + "\r\n";
			}
			bookMarksStore["advice_contentd" + key] = adviceInfo;
		}
  	}  
    //彩打的文档标题
    bookMarksStore["documentName"] = documentName;
    return bookMarksStore;
}

/**
 * word模版书签替换书签
 */
function writeBookMarks(projectPath,fileName,documentName){
    try{
    	var formKey = $("#bizFormKey").val();
    	var formId = $("#bizFormId").val();
    	var printFileName=fileName || formKey;
		var docPath = projectPath+"/customWord/" + printFileName + ".doc";
        // 打开指定路径文档
		var isSuccess = TANGER_OCX_DoOpen_WriteDocPath(docPath);
        // 查询指定表单的书签数据
		var bookMarksStore = queryBookMarksStore(formKey, formId,documentName);
        // 获取当前文档引用
		var doc = TANGER_OCX_OBJ.ActiveDocument;
        // 遍历指定表单的书签数据
		for(var key in bookMarksStore){
			//当前文档存在对应书签时，进行文档书签赋值
			if(doc.BookMarks.Exists(key)){
				TANGER_OCX_OBJ.SetBookmarkValue(key, String(bookMarksStore[key]));
			}
		}
	}catch(err){
		msgWin("错误："+err.number+":"+err.description,2);
	}
}
//保存处理单word形式的文件至服务器
function formSaveAsWordToServer(singlePath,uploadFileName,singlePath){
    try{
    	writeBookMarks();
	
		//上传服务器 开始
		//========================================================================
		var title = pageframe.window.getFormValue("DOCUMENT_TITLE") || 'untitle';

		var name=singlePath;
		var orgName=name.substring(name.lastIndexOf("/")+1,name.lastIndexOf("."))+".doc";
		var retHTML = TANGER_OCX_OBJ.saveToURL(
			global_var_CTX+"/documentOut/content?cover="+uploadFileName+"&ifAdd=true&orgPath="+singlePath, //提交到的url地址
			"EDITFILE", //文件域的id，类似<input type=file id=upLoadFile 中的id
				"",
				orgName,    //上传文件的名称，类似<input type=file 的value
			0           //与控件一起提交的表单id，也可以是form的序列号，这里应该是0.
			); 
		//上传服务器 结束
		//========================================================================
		var newFilePath = retHTML.split("|")[3];

		// 返回路径
		return newFilePath;

	}catch(err){
		msgWin("错误："+err.number+":"+err.description,2);
	}finally{
		msgWin("操作成功！",2);
	}
	return "";
}
//处理单导出代码
function expSingle(){
	TANGER_OCX_DoOpen_WriteDocPath(formSaveAsWordToServer());			
}
//打印处理单
function printSingle(){
	// 打开文档
	TANGER_OCX_DoOpen_WriteDocPath(formSaveAsWordToServer());
}